﻿using WatchDog;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Collections;
using WatchDog.Core;
using System.Threading;

namespace WatchDog.WinForm
{
    public partial class Form1 : Form
    {
        string serviceFilePath = Path.Combine(Application.StartupPath, "WatchDog.WinService.exe");
        string serviceName = "ZWatchDog";
        private FileService service = new FileService();
        private System.Timers.Timer _timer;


        public Form1()
        {
            InitializeComponent();
            using (var client = new SqliteDbContext())
            {
                client.Database.EnsureCreated();
            }
            dataGridView1.ReadOnly = true;
            //dataGridView1.AutoGenerateColumns = false;
            //dataGridView1.Enabled = false;
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;

            


            dataGridView1.RowPostPaint += (s, e) =>
            {
                //获取行对象
                var row = dataGridView1.Rows[e.RowIndex];
                //对行的第一列value赋值
                row.Cells[0].Value = row.Index + 1;
            };


            _timer = new System.Timers.Timer(1000) { AutoReset = true };
            _timer.Elapsed += (sender, eventArgs) =>
            {
                UpdateDataGridView();

                UpdateServiceStatus();
            };

            this.VisibleChanged += (s, e) =>
            {
                if (this.Visible)
                    _timer.Start();
                else _timer.Stop();

            };
        }

        public void UpdateServiceStatus()
        {
            this.Invoke(new Action(() =>
            {
                if (ServicesManage.IsServiceExisted(serviceName))
                {
                    var status = GetServiceStatus(); //Running Stopped 
                    if (status == "Running")
                    {
                        this.label1.ForeColor = Color.Green;
                        this.label1.Text = "Running";
                    }
                    else if (status == "Stopped")
                    {
                        this.label1.ForeColor = Color.Blue;
                        this.label1.Text = "Stopped";
                    }
                    else
                    {
                        this.label1.ForeColor = Color.Yellow;
                        this.label1.Text = status;
                    }
                }
                else
                {
                    this.label1.ForeColor = Color.Red;
                    this.label1.Text = "服务未安装";
                }
            }));
        }

        private void UpdateDataGridView()
        {
            try
            {
                this.Invoke(new Action(() =>
                {
                    var index = 0;
                    if (dataGridView1.SelectedRows.Count > 0)
                        index = dataGridView1.SelectedRows[0].Index;//.DataBoundItem as FileView;

                    dataGridView1.DataSource = null;
                    var list = new List<FileView>();
                    foreach (var item in service.GetFileInfo())
                    {
                        list.Add(new FileView
                        {
                            Id = item.Id,
                            位置 = item.FilePath,
                            名称 = item.FileName,
                            状态 = ProcessHelper.IsStarting(item.FilePath) ? "运行中" : "未运行",
                            运行时长_分 = ProcessHelper.GetStatus(item.FilePath),
                            自动启动 = item.AutoStart == true ? "是" : "否"
                        });
                    }
                    dataGridView1.DataSource = list;

                    if (index > 0)
                        dataGridView1.Rows[index].Selected = true;

                    dataGridView1.AutoResizeColumn(0, DataGridViewAutoSizeColumnMode.DisplayedCells);
                    dataGridView1.AutoResizeColumn(1, DataGridViewAutoSizeColumnMode.DisplayedCells);
                    dataGridView1.AutoResizeColumn(2, DataGridViewAutoSizeColumnMode.DisplayedCells);
                    dataGridView1.AutoResizeColumn(3, DataGridViewAutoSizeColumnMode.DisplayedCells);
                    dataGridView1.AutoResizeColumn(4, DataGridViewAutoSizeColumnMode.DisplayedCells);
                }));
            }
            catch (Exception ex)
            {

            }
        }

        private string GetServiceStatus()
        {
            try
            {
                var serviceController = new ServiceController(serviceName);
                return serviceController.Status.ToString();
            }
            catch (Exception)
            {
                return "";
            }
        }

        private void add_Click(object sender, EventArgs e)
        {
            var s = new SettingForm();
            var xx = s.ShowDialog();
        }

        private void del_Click(object sender, EventArgs e)
        {
            FileView delModel = null;
            if (dataGridView1.SelectedRows.Count > 0)
            {
                delModel = dataGridView1.SelectedRows[0].DataBoundItem as FileView;
            }
            if (delModel == null)
            {
                MessageBox.Show("请选择要删除的数据行");
                return;
            }


            var btn = MessageBoxButtons.YesNoCancel;
            if (MessageBox.Show("确定要删除 " + delModel.名称 + " 吗？", "删除数据", btn) == DialogResult.Yes)
            {
                service.Del(delModel.Id);
            }
        }
        private void buttonStop_Click(object sender, EventArgs e)
        {
            FileView delModel = null;
            if (dataGridView1.SelectedRows.Count > 0)
            {
                delModel = dataGridView1.SelectedRows[0].DataBoundItem as FileView;
            }
            if (delModel == null)
            {
                MessageBox.Show("请选择要停止运行的数据行");
                return;
            }


            var btn = MessageBoxButtons.YesNoCancel;
            if (MessageBox.Show("确定要停止 " + delModel.名称 + " 吗？", "停止", btn) == DialogResult.Yes)
            {
                service.Update(delModel.Id, false);
                ProcessHelper.Stop(delModel.位置);
            }
        }

        private void buttonAuto_Click(object sender, EventArgs e)
        {
            FileView delModel = null;
            if (dataGridView1.SelectedRows.Count > 0)
            {
                delModel = dataGridView1.SelectedRows[0].DataBoundItem as FileView;
            }
            if (delModel == null)
            {
                MessageBox.Show("请选择要切换的数据行");
                return;
            }

            service.Update(delModel.Id, delModel.自动启动 != "是");
        }

        //主窗体关闭时不退出应用程序 隐藏即可
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //窗体关闭原因为单击"关闭"按钮或Alt+F4  
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;           //取消关闭操作 表现为不关闭窗体  
                this.Hide();               //隐藏窗体  
            }
        }
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.Icon.Dispose();
            this.notifyIcon1.Visible = false;
            this.notifyIcon1.Dispose();
        }

        #region 任务栏
        //任务栏图标上左键双击 —— 显示主界面
        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
            this.Activate();
        }
        //任务栏图标上右键 —— 显示菜单 
        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                //还原窗体显示    
                WindowState = FormWindowState.Normal;
                //激活窗体并给予它焦点
                this.Activate();
                ////任务栏区显示图标
                //this.ShowInTaskbar = true;
                ////托盘区图标隐藏
                //notifyIcon1.Visible = false;
            }
        }
        #endregion

        #region 任务栏右键菜单

        private void 显示主程序ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
            this.Activate();
        }

        private void 安装服务toolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (ServicesManage.IsServiceExisted(serviceName))
                ServicesManage.UninstallService(serviceName);
            ServicesManage.InstallService(serviceFilePath);
            MessageBox.Show("服务安装成功...");
        }

        private void 启动服务toolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (ServicesManage.IsServiceExisted(serviceName))
            {
                ServicesManage.ServiceStart(serviceName);
                MessageBox.Show("启动服务成功...");
            }
        }

        private void 停止服务toolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (ServicesManage.IsServiceExisted(serviceName))
            {
                ServicesManage.ServiceStop(serviceName);
                MessageBox.Show("停止服务成功...");
            }
        }

        private void 卸载服务toolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (ServicesManage.IsServiceExisted(serviceName))
            {
                ServicesManage.ServiceStop(serviceName);
                ServicesManage.UninstallService(serviceFilePath);
                MessageBox.Show("卸载服务成功...");
            }
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要退出程序?", "安全提示",
                        System.Windows.Forms.MessageBoxButtons.YesNo,
                        System.Windows.Forms.MessageBoxIcon.Warning)
                == System.Windows.Forms.DialogResult.Yes)
            {
                notifyIcon1.Visible = false;   //设置图标不可见  
                this.Close();                  //关闭窗体  
                this.Dispose();                //释放资源  
                Application.Exit();            //关闭应用程序窗体  
                notifyIcon1.Dispose();
            }
        }
        #endregion


    }

    public class FileView
    {
        public int Id { get; set; }
        public string 名称 { get; set; }

        public string 状态 { get; set; }

        public double 运行时长_分 { get; set; }

        public string 自动启动 { get; set; }    
        
        public string 位置 { get; set; }
    }

}
